import Cookies from 'js-cookie';
import { IntlFormatters } from 'react-intl';
import { request } from '@inbiz/utils';
import { RequestMethod } from 'umi-request';
export class CommonService {
  request: RequestMethod = request;
  intl: IntlFormatters;
  constructor(props: { intl: IntlFormatters }) {
    this.intl = props.intl;
  }
}

export default class EformSelectFolderService extends CommonService {
  remoteServer = {
    //第三方服务器， 用于文件摆渡
    url: '',
    token: '',
  };
  constructor(props: { intl: IntlFormatters; remoteServer?: { url: string; token: string } }) {
    super(props);
    if (props.remoteServer && props.remoteServer.url) {
      this.remoteServer = {
        ...props.remoteServer,
        url:
          props.remoteServer.url[props.remoteServer.url.length - 1] === '/'
            ? props.remoteServer.url.slice(0, -1)
            : props.remoteServer.url,
      };
    } else {
      this.remoteServer = {
        url: '',
        token: Cookies.get('token') as string,
      };
    }
  }
  getTopFolders(params: {
    topFolderIds: number | number[];
    showEnterprise: boolean;
    showPerson?: boolean;
    showTeam?: boolean;
  }) {
    let args = {
      token: this.remoteServer.token,
      topFolderIds: params.topFolderIds,
      showEnterpriseFolder: params.showEnterprise,
      showPersonalFolder: params.showPerson,
      showTeamFolder: params.showTeam,
      permValue: 1,
      timestamp: new Date().getTime(),
    };
    return this.request(this.remoteServer.url + '/api/FolderRead/GetEdoc2FolderInfoByPage', {
      method: 'GET',
      params: args,
    });
  }

  getFolderChilren(params: { folderId: number; pageNum: number; pageSize: number }) {
    let args = {
      token: this.remoteServer.token,
      topFolderId: params.folderId,
      pageNum: params.pageNum,
      pageSize: params.pageSize,
    };

    return this.request(this.remoteServer.url + '/api/FolderRead/GetChildrenFolderListByPage', {
      method: 'GET',
      params: args,
    });
  }
  //新接口，返回附带folderUID
  getFolderChildrens(params: { folderId: number; pageNum: number; pageSize: number }) {
    let args = {
      token: this.remoteServer.token,
      topFolderId: params.folderId,
      pageIndex: params.pageNum,
      pageSize: params.pageSize,
    };

    return this.request(this.remoteServer.url + '/api/FolderRead/GetFolderChildren', {
      method: 'GET',
      params: args,
    }).then((res) => {
      let resArr = {};
      Object.keys(res.Info).forEach((key) => {
        resArr[key.toLowerCase()] = res.Info[key];
      });

      res.Info = resArr;

      let arr = res.Info?.children?.map((item: any) => {
        let data = {};
        Object.keys(item).forEach((key) => {
          data[key.toLowerCase()] = item[key];
        });
        return data;
      });
      res.Info.children = arr;
      return res;
    });
  }

  getFileAndFolderChildren(params: { folderId: number; pageNum: number; pageSize: number }) {
    // basic:name 名称
    // basic:code 编号
    // basic:size 大小
    // basic:creator 创建人
    // basic:editor 修改人
    // basic:modifyTime 修改时间
    // basic:createTime 创建时间
    // basic:state 状态
    // basic:version 版本
    // basic:remark 备注
    // basic:securityLevel 密级
    let args = {
      folderId: params.folderId,
      pageNum: params.pageNum,
      pageSize: params.pageSize,
      sortField: 'basic:name',
      sortDesc: false,
      token: Cookies.get('token'),
    };

    return this.request(this.remoteServer.url + '/api/services/Doc/GetFileAndFolderList', {
      method: 'GET',
      params: args,
    }).then((res) => {
      let resData: any[] = [];
      if (res.result == 0) {
        resData = [...res.data.FoldersInfo, ...res.data.FilesInfo, res.data.Settings.TotalCount];
      }
      return resData;
    });
  }

  getFolderChildrenFiles(params: { folderId: number; pageSize: number; pageNum: number }) {
    let args = {
      token: this.remoteServer.token,
      folderId: params.folderId,
      pageSize: params.pageSize,
      pageNum: params.pageNum,
      sortField: 'FileName',
      sortDesc: false,
      onlyShowFileType: '',
    };
    return this.request(this.remoteServer.url + '/api/FileRead/GetChildFileListPageByFolderId', {
      method: 'POST',
      params: args,
    }).then((res) => {
      let arr = res.Info?.map((item: any) => {
        let data = {};
        Object.keys(item).forEach((key) => {
          data[key.toLowerCase()] = item[key];
        });
        return data;
      });
      res.Info = arr;
      return res;
    });
  }

  GetFolderChild(params: {
    curFolderId: number;
    pageNum: number;
    pageSize: number;
    isPerson: boolean;
    sortKey?: string;
    sortDesc?: boolean;
  }): Promise<{
    result: number;
    docListInfo: {
      [x: string]: any;
      FoldersInfo: FolderPanel.IFolder[];
      FilesInfo: FolderPanel.IFile[];
      Settings: FolderPanel.IPagination;
    };
    thisFolder: Omit<FolderPanel.IFolder, 'favoriteId' | 'favoriteType'>;
  }> {
    let argsXml = '';
    argsXml += '<GetListArgs>';
    argsXml += `<PageNum>${params.pageNum}</PageNum>`;
    argsXml += `<PageSize>${params.pageSize}</PageSize>`;
    if (params.sortKey) {
      argsXml += `<SortInfoName>${params.sortKey}</SortInfoName><SortDesc>${
        params.sortDesc == null ? 'true' : params.sortDesc
      }</SortDesc>`;
    }
    argsXml += '</GetListArgs>';
    return this.request(this.remoteServer.url + `/WebCore`, {
      method: 'POST',
      requestType: 'form',
      data: {
        module: 'WebClient',
        fun: 'GetFolderChildren',
        fid: params.curFolderId,
        argsXml: argsXml,
        isPerson: params.isPerson,
        noCalcPerm: true,
      },
    });
  }
  searchFolders(params: {
    folderId: number;
    pageNum: number;
    pageSize: number;
    keyword: string;
    isSelect: boolean;
    isPerson: boolean;
  }) {
    let args = {
      module: 'WebClient',
      fun: 'GetMapSearchResultList',
      mnId: 0,
      docViewId: 0,
      argsXml: `<GetListArgs><PageNum>${params.pageNum}</PageNum><PageSize>${params.pageSize}</PageSize></GetListArgs>`,
      metaDataSearch: false,
      startNum: 0,
      searchType: 'MetaFolder',
      searchLocation: params.isPerson ? 'person' : 'enterprise',
      searchXml: `{"from":${(params.pageNum - 1) * params.pageSize},"size":${
        params.pageSize
      },"_source":{"excludes":["filecontent"]},"sort":[{"_score":{"order":"desc"}}],"query":{"query_string":{"query":"NOT folderid:${
        params.folderId
      } AND ${`${
        params.isSelect
          ? `(folderpath:(${params.folderId}))`
          : `(parentfolderid:(${params.folderId}))`
      }`} AND (foldername:(${params.keyword}) OR suggest:(*${
        params.keyword
      }*))","default_operator":"AND"}},"highlight":{"fields":{"filename":{},"filecontent":{"type":"fvh"}},"pre_tags":"<span class='Highlighter'>","post_tags":"</span>","number_of_fragments":3,"no_match_size":250}}`,
    };
    return this.request(this.remoteServer.url + '/WebCore', {
      method: 'POST',
      data: args,
      requestType: 'form',
      headers: { 'X-Requested-With': 'XMLHttpRequest' },
    }).then((res) => {
      let arr = res.docListInfo.FoldersInfo?.map((item: any) => {
        let data = {};
        Object.keys(item).forEach((key) => {
          data[key.toLowerCase()] = item[key];
        });
        return data;
      });
      res.docListInfo.FoldersInfo = arr;
      return res;
    });
  }
  searchFiles(params: {
    folderId: number;
    pageNum: number;
    pageSize: number;
    keyword: string;
    isSelect: boolean;
    isPerson?: boolean;
  }) {
    let args = {
      module: 'WebClient',
      fun: 'GetMapSearchResultList',
      mnId: 0,
      docViewId: 0,
      argsXml: `<GetListArgs><PageNum>${params.pageNum}</PageNum><PageSize>${params.pageSize}</PageSize></GetListArgs>`,
      metaDataSearch: false,
      startNum: 0,
      searchType: 'MixFile',
      searchLocation: params.isPerson ? 'person' : 'enterprise',
      searchXml: `{"from":${(params.pageNum - 1) * params.pageSize},"size":${
        params.pageSize
      },"_source":{"excludes":["filecontent"]},"sort":[{"_score":{"order":"desc"}}],"query":{"query_string":{"query":"${`${
        params.isSelect
          ? `(filepath:(${params.folderId}) OR masterfilepath:(${params.folderId}))`
          : `(parentfolderid:(${params.folderId}))`
      }`} AND (filename:(${params.keyword}) OR suggest:(*${
        params.keyword
      }))","default_operator":"AND"}},"highlight":{"fields":{"filename":{},"filecontent":{"type":"fvh"}},"pre_tags":"<span class='Highlighter'>","post_tags":"</span>","number_of_fragments":0,"no_match_size":250}}`,
    };
    return this.request(this.remoteServer.url + '/WebCore', {
      method: 'POST',
      data: args,
      requestType: 'form',
      headers: { 'X-Requested-With': 'XMLHttpRequest' },
    }).then((res) => {
      let arr = res.docListInfo.FilesInfo?.map((item: any) => {
        let data = {};
        Object.keys(item).forEach((key) => {
          data[key.toLowerCase()] = item[key];
        });
        return data;
      });
      res.docListInfo.FilesInfo = arr;
      return res;
    });
  }

  getChildrenFolderListByPage(params: { topFolderId: string | number; pageNum: number }) {
    return this.request(this.remoteServer.url + '/api/FolderRead/GetChildrenFolderListByPage', {
      method: 'POST',
      requestType: 'form',
      data: params,
    }).then((res) => JSON.parse(res));
  }

  getHotWordsList(params: {
    keyword: string;
    type: number;
    curFolderId: number;
    searchLocation: string;
  }) {
    let args = {
      ...params,
      fun: 'GetHotWordsList',
      module: 'WebClient',
    };
    return this.request(this.remoteServer.url + '/WebCore', {
      requestType: 'form',
      method: 'POST',
      data: args,
    });
  }
  SaveSearchData(params: { keyWord: string }) {
    let args = {
      ...params,
      fun: 'SaveSearchData',
      module: 'MetaDataManager',
    };
    return this.request(this.remoteServer.url + '/WebCore', {
      requestType: 'form',
      method: 'POST',
      data: args,
    });
  }
  GetFolderById(params: { folderId: number }) {
    let args = {
      ...params,
      module: 'WebClient',
      fun: 'GetFolderById',
    };
    return this.request(this.remoteServer.url + '/WebCore', {
      requestType: 'form',
      method: 'POST',
      data: args,
    });
  }
}

export async function getDocumentInfoByFile(docmentIds: string, props: any) {
  let url = `/inbiz/api/services/modelengine/v${InbizConfig.API_VERSION}/control/getDocumentInfo`;
  if (props.childModelConfig) {
    url = `/inbiz/api/services/modelengine/v${InbizConfig.API_VERSION}/business/selectDatas`;
  }
  if (docmentIds && !props.childModelConfig) {
    return request
      .post(url, {
        data: [
          {
            docmentIds,
            docType: '1',
          },
        ],
      })
      .then((res) => {
        let arr = res.data?.FileInfoList?.map((item: any) => {
          let data = {};
          Object.keys(item).forEach((key) => {
            data[key.toLowerCase()] = item[key];
          });
          return data;
        });
        return arr;
      });
  } else if (props.childModelConfig) {
    return request
      .post(url, {
        data: {
          name: props.storageConfig.name,
          data: {
            ref_id: props.inbiz?.queryData?.id,
            controlid: props.controlId,
          },
        },
      })
      .then((res) => {
        const list: Array<any> = res?.data ?? [];
        const result = list.map((ele) => ({
          // id: ele.id,
          // fileid: ele.fileid,
          // filename: ele.filename,
          // status: 'upload successful',
          // filelastsize: ele.filelastsize,
          ...ele,
        }));
        return result;
      });
  } else {
    return {
      data: {
        FolderInfoList: [],
        FileInfoList: [],
      },
      dataDescription: '',
      message: '',
      result: 0,
    };
  }
}

export async function getDocumentInfoByFolder(docmentIds: string, props: any) {
  const host = props?.remoteServer?.url
    ? props.remoteServer.url[props.remoteServer.url.length - 1] === '/'
      ? props.remoteServer.url.slice(0, -1)
      : props.remoteServer.url
    : '';
  let url =
    host + `/inbiz/api/services/modelengine/v${InbizConfig.API_VERSION}/control/getDocumentInfo`;
  if (props.childModelConfig) {
    url = `/inbiz/api/services/modelengine/v${InbizConfig.API_VERSION}/business/selectDatas`;
  }
  if (docmentIds && !props.childModelConfig) {
    return (
      !host
        ? request.post(url, {
            data: [
              {
                docmentIds,
                docType: '0',
              },
            ],
          })
        : fetch(url + '?token=' + props.remoteServer.token, {
            method: 'POST',
            body: JSON.stringify([
              {
                docmentIds,
                docType: '0',
              },
            ]),
          }).then((res) => res.json())
    ).then((res) => {
      let arr = res.data?.FolderInfoList?.map((item: any) => {
        let data = {};
        Object.keys(item).forEach((key) => {
          data[key.toLowerCase()] = item[key];
        });
        return data;
      });
      return arr;
    });
  } else if (props.childModelConfig) {
    return request
      .post(url, {
        data: {
          name: props.storageConfig.name,
          data: {
            ref_id: props.inbiz?.queryData?.id,
            controlid: props.controlId,
          },
        },
      })
      .then((res) => {
        const list: Array<any> = res?.data ?? [];
        const result = list.map((ele) => ({
          ...ele,
        }));
        return result;
      });
  } else {
    return {
      data: {
        FolderInfoList: [],
        FileInfoList: [],
      },
      dataDescription: '',
      message: '',
      result: 0,
    };
  }
}
